//
//  PPCreateAlbumViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/28/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumContentViewController.h"
#import "PPAlbumContentPrivacyViewController.h"
#import "PPAlbumContentOrderViewController.h"
#import "PPAlbumContentCommentPermissionViewController.h"
#import "PPAlbumContentTagsViewController.h"
#import "PPAssetsPickerViewController.h"
#import "PPAlbumContentPictureViewController.h"

#import "PPAlbumContentTableViewPictureRowCell.h"
#import "PPAlbumContentTableViewPictureAddCell.h"
#import "PPAlbumContentTableViewTitleCell.h"
#import "PPAlbumContentTableViewDescriptionCell.h"

#import "PPAlbumContentViewDataSource.h"

#import "PPAlbumModel.h"

#import "PPAlbumManager.h"

#import "PPImageTransaction.h"

@interface PPAlbumContentViewController () <PPAssetsPickerViewControllerDelegate, PPAlbumContentPictureViewControllerDelegate,TZImagePickerControllerDelegate>
@property (readwrite, nonatomic, strong) PPAlbumContentViewDataSource *dataSource;
@end

@implementation PPAlbumContentViewController

- (void)awakeFromNib {
    [super awakeFromNib];

    _dataSource = [[PPAlbumContentViewDataSource alloc] init];
    _dataSource.privacy = @(PPAlbumPrivacyAll);
    _dataSource.permission = @(PPAlbumCommentEnabled);
    _dataSource.order = @(PPAlbumOrderDesc);
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
    
    
    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" titleColor:BLACK action:^{

        DGBlockAlertView *alertView = [DGBlockAlertView alertWithTitle:@"是否退出编辑？" message:nil cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"退出" comfirmBlock:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];

        [alertView show];

    }];

    [self setNavigationRightTitle:@"保存" titleColor:NAV_RightItemColor action:^{
        [weakSelf saveItemDidPressed];
    }];
    
    
    
    
    if (self.images.count > 0) {
        
        for (UIImage *img in self.images) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;
            [_dataSource.images addObject:artwork];
            [_dataSource.insertedImages addObject:artwork];
        }
        
        [self.tableView reloadData];
    }
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.tableView reloadData];
}

- (void)setAuuid:(NSString *)auuid {
    _auuid = auuid;

    if(auuid == nil) {
        return;
    }

    PPAlbumModel *album = [PPAlbumModel find:@{@"auuid" : auuid}];

    _dataSource.title = album.title;
    _dataSource.desc = album.desc;
    _dataSource.privacy = album.privacy;
    _dataSource.permission = album.permission;
    _dataSource.order = album.order;

    NSArray *privacyUserIDs = [album.privacyUserIDs componentsSeparatedByString:@","];

    for(NSInteger index = 0; index < privacyUserIDs.count; index++) {
        NSString *privacyUserID = [privacyUserIDs validStringAtIndex:index];

        if(privacyUserID.length > 0) {
            [_dataSource.privacyUserIDs addSafeObject:privacyUserID];
        }
    }

    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : auuid, @"deleted" : @(NO)}];

    NSArray <PPAlbumTagModel *> *tags = [PPAlbumTagModel where:@{@"auuid" : auuid}];

    [images enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = obj.artwork;
        [_dataSource.images addObject:artwork];
    }];

    [tags enumerateObjectsUsingBlock:^(PPAlbumTagModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAlbumTagElement *tag = [[PPAlbumTagElement alloc] init];
        tag.tagID = obj.tagID;
        tag.name = obj.name;
        [_dataSource.tags addObject:tag];
    }];
}

- (void)saveItemDidPressed {

    if(_dataSource.title.charCount > 16) {
        [self.navigationController.view toastMessage:@"相册名称不能超过16个字符"];
        return;
    }

    if(_dataSource.desc.length > 200) {
        [self.navigationController.view toastMessage:@"相册描述不能超过200个字符"];
        return;
    }

    if(_dataSource.title.length == 0) {
        _dataSource.title = @"未命名图册";
    }

    NSString *coverUUID = nil;

    if(_dataSource.coverUUID != nil) {
        coverUUID = _dataSource.coverUUID;
    } else {
        // 从images里找第一张图作为cover
        BOOL force = NO;
        if(_auuid != nil) {
            PPAlbumModel *album = [PPAlbumModel find:@{@"auuid": _auuid}];
            if(album.coverKey.length == 0 || album.coverHost.length == 0) {
                force = YES;
            }
        } else {
            force = YES;
        }

        if(force) {
            NSArray <PPAbstractArtwork *> *sortedImages = nil;
            if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
                sortedImages = self.dataSource.images;
            } else {
                sortedImages = [self.dataSource.images.reverseObjectEnumerator allObjects];
            }
            coverUUID = sortedImages.firstObject.uuid;
        }
    }

    if(_type == PPAlbumContentViewControllerTypeCreate) {
        [[PPAlbumManager sharedInstance] offlineCreateAlbumWithArtworks:_dataSource.insertedImages tags:_dataSource.tags title:_dataSource.title description:_dataSource.desc order:_dataSource.order permission:_dataSource.permission privacy:_dataSource.privacy privacyUserIDs:_dataSource.privacyUserIDs coverUUID:coverUUID];
    } else {
        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_auuid insertedArtworks:_dataSource.insertedImages modifiedArtworks:_dataSource.modifiedImages deletedArtworks:_dataSource.deletedImages tags:_dataSource.tags title:_dataSource.title description:_dataSource.desc order:_dataSource.order permission:_dataSource.permission privacy:_dataSource.privacy privacyUserIDs:_dataSource.privacyUserIDs coverUUID:coverUUID];
    }

    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch(section) {
        case 0: {
            NSInteger rows = ceil(self.dataSource.images.count/4.0);

            return rows + 2;
        }

        case 1:
        case 2: {
            return 1;
        }

        case 3: {
//            return 4;
            return 1;
        }
    }

    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch(indexPath.section) {
        case 0: {
            if(indexPath.row == 0) {
                return 161;
            } else if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
                if(_dataSource.images.count == 0) {
                    return 0;
                } else {
                    return 12;
                }
            } else {
                return [PPAlbumContentTableViewPictureRowCell heightForNumberOfPictures:_dataSource.images.count boundingSize:CGSizeMake(tableView.width, CGFLOAT_MAX)];
            }

            break;
        }

        case 1: {
            return 46;
        }

        case 2: {
            return 135;
        }

        case 3: {
            return 46;
        }
    }

    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = nil;

    switch(indexPath.section) {
        case 0: {

            if(indexPath.row == 0) {
                identifier = @"addCell";
                break;
            } else if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
                identifier = @"footerCell";
                break;
            } else {
                identifier = @"pictureCell";
                break;
            }

            break;
        }

        case 1: {
            identifier = @"titleCell";
            break;
        }

        case 2: {
            identifier = @"descriptionCell";
            break;
        }

        case 3: {

//            switch(indexPath.row) {
//                case 0: {
//                    identifier = @"tagCell";
//                    break;
//                }

//                case 0: {
                    identifier = @"orderCell";
                    break;
//                }

//                case 2: {
//                    identifier = @"privacyCell";
//                    break;
//                }

//                case 3: {
//                    identifier = @"permissionCell";
//                    break;
//                }

//                default:
//                    break;
//            }

//            break;
        }

        default:
            break;
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];

    __weak typeof(self)weakSelf = self;

    if([identifier isEqualToString:@"addCell"]) {
        [((PPAlbumContentTableViewPictureAddCell *)cell).addButton setActionBlock:^(UIControl *control) {
            ///进入相册
//            PPAssetsPickerViewController *assetsViewController = [[PPAssetsPickerViewController alloc] init];
//            assetsViewController.delegate = weakSelf;
//            assetsViewController.userInfo = @{@"type" : @"addImage"};
//            [weakSelf.navigationController pushViewController:assetsViewController animated:YES];
            [weakSelf selectPhoto];
            
        } forControlEvents:UIControlEventTouchUpInside];
    } else if([identifier isEqualToString:@"pictureCell"]) {
        NSInteger index = (indexPath.row - 1)*4;

        NSArray *sortedImages = nil;

        if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
            sortedImages = self.dataSource.images;
        } else {
            sortedImages = [self.dataSource.images.reverseObjectEnumerator allObjects];
        }

        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork1 = [sortedImages safeObjectAtIndex:index];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork2 = [sortedImages safeObjectAtIndex:index + 1];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork3 = [sortedImages safeObjectAtIndex:index + 2];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork4 = [sortedImages safeObjectAtIndex:index + 3];
    }

    if([cell respondsToSelector:@selector(setDelegate:)]) {
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }

    if([cell respondsToSelector:@selector(setDataSource:)]) {
        [cell performSelector:@selector(setDataSource:) withObject:self.dataSource];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

//    switch(indexPath.section) {
//        case 3: {
//            switch(indexPath.row) {
//                case 0: {
//                    PPAlbumContentTagsViewController *tagsViewController = [[PPAlbumContentTagsViewController alloc] init];
//                    tagsViewController.dataSource = _dataSource;
//                    [self.navigationController pushViewController:tagsViewController animated:YES];
//
//                    break;
//                }
//
//                case 1: {
//                    PPAlbumContentOrderViewController *orderViewController = [[PPAlbumContentOrderViewController alloc] init];
//                    orderViewController.dataSource = _dataSource;
//                    [self.navigationController pushViewController:orderViewController animated:YES];
//
//                    break;
//                }
//
//                case 2: {
    
    
    if (indexPath.section == 3) {
        
//        PPAlbumContentPrivacyViewController *privacyViewController = [[PPAlbumContentPrivacyViewController alloc] init];
//        privacyViewController.dataSource = _dataSource;
//        [self.navigationController pushViewController:privacyViewController animated:YES];
//
        PPAlbumContentOrderViewController *orderViewController = [[PPAlbumContentOrderViewController alloc] init];
        orderViewController.dataSource = _dataSource;
        [self.navigationController pushViewController:orderViewController animated:YES];
    }

//                    break;
//                }
//
//                case 3: {
//                    PPAlbumContentCommentPermissionViewController *persmissionViewController = [[PPAlbumContentCommentPermissionViewController alloc] init];
//                    persmissionViewController.dataSource = _dataSource;
//                    [self.navigationController pushViewController:persmissionViewController animated:YES];
//
//                    break;
//                }
                    
//            }
//        }
//    }
}

#pragma mark - PPCreateAlbumTableViewAlbumCellDelegate

- (void)pictureCell:(PPAlbumContentTableViewPictureRowCell *)pictureCell didSelectDeleteButton:(UIButton *)button atIndex:(NSInteger)index {
    PPAbstractArtwork *artwork = nil;

    switch(index) {
        case 0: artwork = pictureCell.artwork1; break;
        case 1: artwork = pictureCell.artwork2; break;
        case 2: artwork = pictureCell.artwork3; break;
        case 3: artwork = pictureCell.artwork4; break;

        default: break;
    }

    if(artwork == nil) {
        return;
    }

    [_dataSource.deletedImages addObject:artwork];
    [_dataSource.modifiedImages removeObject:artwork];
    [_dataSource.insertedImages removeObject:artwork];
    [_dataSource.images removeObject:artwork];

    [self.tableView reloadData];
}

- (void)pictureCell:(PPAlbumContentTableViewPictureRowCell *)pictureCell didSelectArtworkAtIndex:(NSInteger)index {
    NSArray <PPAbstractArtwork *> *sortedImages = nil;
    if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
        sortedImages = self.dataSource.images;
    } else {
        sortedImages = [self.dataSource.images.reverseObjectEnumerator allObjects];
    }

    PPAbstractArtwork *artwork = nil;

    switch(index) {
        case 0: artwork = pictureCell.artwork1; break;
        case 1: artwork = pictureCell.artwork2; break;
        case 2: artwork = pictureCell.artwork3; break;
        case 3: artwork = pictureCell.artwork4; break;

        default: break;
    }

    if(artwork == nil) {
        return;
    }

    index = [sortedImages indexOfObject:artwork];

    PPAlbumContentPictureViewController *pictureViewController = [[PPAlbumContentPictureViewController alloc] init];
    pictureViewController.artworks = sortedImages;
    pictureViewController.index = index;
    pictureViewController.view.backgroundColor = WHITE;
    pictureViewController.delegate = self;
    [self.navigationController pushViewController:pictureViewController animated:YES];
}

#pragma mark - PPAssetsPickerViewControllerDelegate

- (void)assetsPickerViewControllerDidPressCancel:(PPAssetsPickerViewController *)assetsPickerViewController {
    [self.navigationController popToViewController:self animated:YES];
}

- (void)assetsPickerViewControllerDidPressConfirm:(PPAssetsPickerViewController *)assetsPickerViewController {
    [assetsPickerViewController.selectedAssets enumerateObjectsUsingBlock:^(ALAsset *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.uuid = [NSString uuid];
        artwork.image = [obj.image fixOrientation];
        artwork.created = YES;
        [_dataSource.images addObject:artwork];
        [_dataSource.insertedImages addObject:artwork];

        [self.tableView reloadData];
    }];

    [self.navigationController popToViewController:self animated:YES];
}

#pragma mark - PPAlbumContentPictureViewControllerDelegate

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setArtworkAsCover:(PPAbstractArtwork *)artwork {
    self.dataSource.coverUUID = artwork.uuid;
}

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setDescription:(NSString *)description forArtwork:(PPAbstractArtwork *)artwork {
    artwork.desc = description;

    if(![self.dataSource.modifiedImages containsObject:artwork]) {
        [self.dataSource.modifiedImages addObject:artwork];
    }
}


///MARK:调用相册
- (void)selectPhoto{
    
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:50 delegate:self];
    imagePickerVc.naviBgColor = WHITE;
    imagePickerVc.naviTitleColor = BLACK;
    imagePickerVc.naviTitleFont = PPFONT(@"Helvetica-Bold", 17);
    imagePickerVc.barItemTextColor = BLACK;
    imagePickerVc.barItemTextFont = PPFONTSIZE(16);
    imagePickerVc.allowPickingVideo = NO;
    WEAKSELF
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
        for (UIImage *img in photos) {

            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;
            [_dataSource.images addObject:artwork];
            [_dataSource.insertedImages addObject:artwork];
        }
        
        [weakSelf.tableView reloadData];
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
@end
